﻿using KuaFu.CardIssuing.OpenApi.Args.Authorization;
using KuaFu.CardIssuing.OpenApi.Result;
using KuaFu.CardIssuing.OpenApi.Utils;
using KuaFu.Core;
using KuaFu.Core.Helper;
using KuaFu.Extensions.Base;
using KuaFu.Shared;
using KuaFu.Shared.UserCenterService.Services.Merchant;
using KuaFu.Strategy.Cache;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace KuaFu.CardIssuing.OpenApi.Controllers
{
    [Route("api/authorization")]
    public class AuthorizationController : BaseApiController
    {
        private readonly IServiceProvider _serviceProvider;
        private const string LOGIN_KEY = "Login_";
        private readonly ICache _cache;

        public AuthorizationController(IServiceProvider serviceProvider, ICache cache)
        {
            _serviceProvider = serviceProvider;
            _cache = cache;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        /// <exception cref="KuaFuException"></exception>
        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<ApiResult<AuthLoginResult>> LoginAsync([FromBody] LoginArgs args)
        {

            if(args.MerchantId == 0 || args.Nonce.IsNullOrEmpty() || args.TimeStamp==0|| args.Sign.IsNullOrEmpty())
                throw new KuaFuException("参数错误");
            

            if ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(args.TimeStamp)).TotalMinutes > 5)
                throw new KuaFuException("时间戳超时");

            var merchantInfo = await _serviceProvider.GetRequiredService<GetMerchantInfoSecretKeyService>().ExecuteAsync(new GetMerchantInfoSecretKeyArgument(args.MerchantId));

            var originString = $"{args.MerchantId}&{args.TimeStamp}&{args.Nonce}&{merchantInfo.Data.SecretKey}";
            var sign = SignHelper.MakeSign(originString);
            if(sign != args.Sign)
                throw new KuaFuException("签名错误");

            var token = $"{args.MerchantId}{StringHelper.GetGUID()}";
            await _cache.InsertAsync($"{LOGIN_KEY}{token}", merchantInfo.Data.LoginUser, TimeSpan.FromDays(1),false,true);
            return new ApiResult<AuthLoginResult>(new AuthLoginResult(token));
        }
    }
}
